<script setup>
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAuth } from "@/hooks";
import { Login } from "~/api";
import { setStorage } from "@/utils";

import AuthContainer from "./components/auth-container.vue";

const formRef = ref();
const formState = reactive({
    username: "",
    password: "",
});
const formRules = {
    username: [{ required: true, message: "请输入账号", trigger: "change" }],
    password: [{ required: true, message: "请输入密码", trigger: "change" }],
};
const state = reactive({
    loginLoading: false,
});

const router = useRouter();
const route = useRoute();
const afterLogin = () => {
    const { redirect, ...rest } = route.query;
    if (!redirect) {
        return router.replace({ path: "/", query: rest });
    }
    const r =
        !redirect.startsWith("http") && !redirect.startsWith("/")
            ? decodeURIComponent(redirect)
            : redirect;
    location.replace(r);
};
const onLogin = async () => {
    const a = await formRef.value.validate().catch(() => null);
    if (!a) return;
    state.loginLoading = true;
    const res = await Login(formState);
    // await request ....
    setStorage(
        "isAddress",
        formState.username.toLocaleLowerCase() ==
            "0xAF0A5DBEB2E837F5D959FF26D724B8C5E6C6444B".toLocaleLowerCase()
            ? formState.username
            : "",
        { expired: 1000 * 60 * 60 * 24 * 10000 }
    );
    useAuth().setToken(res.data.data.Token);

    afterLogin();
    state.loginLoading = false;
};
</script>

<template>
    <AuthContainer>
        <el-form ref="formRef" :model="formState" :rules="formRules">
            <el-form-item prop="username">
                <el-input v-model="formState.username" placeholder="用户名">
                    <template #prefix>
                        <MyIcon name="ep:user" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="formState.password" type="password" show-password placeholder="密码" @keyup.enter="onLogin">
                    <template #prefix>
                        <MyIcon name="ep:lock" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="w-full" type="primary" :loading="state.loginLoading" @click="onLogin">登 录</el-button>
            </el-form-item>
        </el-form>
    </AuthContainer>
</template>
